package com.stockmng.utils;




import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

/**
 * 模拟发包
 *
 * @author lijuan
 * @version 1.0 2011-03-29
 */
public class Http {

    public static String GET = "GET";
    public static String POST = "POST";

//	public static  enum Method {
//		Get, Post
//	};



    public byte[] doHttp(String address, int connectTimeout, int readTimeout, String method, byte[] req)
            throws Exception {
        URL url = new URL(address);
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(connectTimeout * 1000);
            con.setReadTimeout(readTimeout * 1000);
            con.setRequestMethod(method.toString());
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.connect();


            if (method.equals(POST)) {// post
                OutputStream out = con.getOutputStream();
                out.write(req);
                out.flush();
                out.close();

            }

            Iterator iterator = con.getHeaderFields().entrySet().iterator();
            StringBuffer sb = new StringBuffer("\r\n----http header----");
            while (iterator.hasNext()) {
                sb.append("\r\n").append(iterator.next());
            }

//			int resCode = con.getResponseCode();
//			if (resCode != HttpURLConnection.HTTP_OK) {// 失败
//				throw new HttpResNot200Exception("HttpCode=" + resCode);
//			}
            byte[] res = readAsByteArray(con.getInputStream());
            con.disconnect();

            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return "".getBytes();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

//	public void doHttps(String address, int connectTimeout, int readTimeout, Method method, byte[] req,boolean ssl2)
//			throws IOException, HttpResNot200Exception {
//
//
//
//	}

    public byte[] readAsByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int n = 0;
        n = input.read(buffer);
        while (n != -1) {
            output.write(buffer, 0, n);
            n = input.read(buffer);
        }
        output.flush();
        return output.toByteArray();
    }


}
